from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from datetime import datetime, timedelta
# Create your views here.

def index(request):
    return render(request,'booktest/index.html')

def showarg(request,num):
    return HttpResponse(num)

def login(request):
    '''显示登录页面'''
    # 判断用户是否登录
    if request.session.has_key('islogin'):
        return redirect('/index')
    else:
        # 获取登录用户名
        if 'username' in request.COOKIES:
            username = request.COOKIES['username']
        else:
            username = ''

        return render(request,'booktest/login.html',{'username':username})


def login_check(request):
    '''登录校验视图'''
    #request.POST保存的是post方式提交的参数 QueryDict
    # request.GET保存的是get方式提交的参数
    #1. 获取提交的用户名和密码
    username=request.POST.get('username')
    password=request.POST.get('password')
    remember = request.POST.get('remember')
    print(remember)
    #2. 进行登录的校验
    #实际开发：根据用户和密码查找数据库
    #模拟：smart 123
    if username=='smart' and password=='123':
        #用户名密码正确，跳转到首页
        response = redirect('/index')
        if remember == 'on':
            # 设置cookie 过期时间为1周
            response.set_cookie('username',username,max_age=7*24*3600)

        # 记住用户登录状态
        request.session['islogin'] =True
        return response
    else:
        #用户名或密码错误，跳转到登录页面
        return redirect('/login')

def ajax_test(request):
    return render(request,'booktest/test_ajax.html')

def ajax_handle(request):
    print('66')
    return JsonResponse({'res':1})

def login_ajax(request):
    '''ajax登录页面'''
    return render(request, 'booktest/login_ajax.html')

def login_ajax_check(request):
    '''ajax登录页面'''
    username=request.POST.get('username')
    password = request.POST.get('password')
    if username == 'smart' and password== '123':
        return JsonResponse({'res':1}) #ajax请求在后台，不要返回页面或者重定向
    else:
        return JsonResponse({'res':0})


def set_cookie(request):
    res=HttpResponse('设置setcookie')
    res.set_cookie('num',1,max_age=14*24*3600) #设置一个cookie值 name:num vaulue:1 max_age过期时间
     # res.set_cookie('num',1,expires=datetime.now()+timedelta(days=14))
    return res

def get_cookie(request):
    num = request.COOKIES['num']
    return HttpResponse(num)


def set_session(request):
    '''设置session'''
    request.session['username'] = 'smart'
    request.session['age'] = 18
    request.session.set_expiry(5)
    return HttpResponse('设置session')

def get_session(request):
    '''获取session'''
    username = request.session['username']
    age = request.session['age']
    return HttpResponse(username+':'+str(age))

def clear_session(request):
    '''清除所有session'''
    request.session.clear() # clear 删除值的部分
    request.session.flush() # flush 删除整条数据
    return HttpResponse('清除成功')




